<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="navbar-left" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <view class="navbar-title">个人信息</view>
      <view class="navbar-right"></view>
    </view>
    
    <!-- 加载中 -->
    <view v-if="loading" class="loading-container">
      <uni-icons type="spinner-cycle" size="30" color="#FF8C42"></uni-icons>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 用户信息表单 -->
    <view v-else class="user-form">
      <!-- 头像 -->
      <view class="form-item avatar-item">
        <text class="form-label">头像</text>
        <view class="avatar-wrapper" @click="chooseAvatar">
          <image class="avatar" :src="userDetail.avatarUrl ? (BASE_URL + userDetail.avatarUrl) : '/static/placeholder.png'" mode="aspectFill"></image>
          <view class="avatar-edit">
            <uni-icons type="camera" size="20" color="#fff"></uni-icons>
          </view>
        </view>
      </view>
      
      <!-- 用户名 -->
      <view class="form-item">
        <text class="form-label">用户名</text>
        <text class="form-value">{{ userDetail.username }}</text>
      </view>
      
      <!-- 手机号 -->
      <view class="form-item" @click="showEditModal('phone')">
        <text class="form-label">手机号</text>
        <view class="form-value-wrapper">
          <text class="form-value">{{ userDetail.phone }}</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
      
      <!-- 邮箱 -->
      <view class="form-item" @click="showEditModal('email')">
        <text class="form-label">邮箱</text>
        <view class="form-value-wrapper">
          <text class="form-value">{{ userDetail.email || '未设置' }}</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
      
      <!-- 修改密码 -->
      <view class="form-item" @click="showEditModal('password')">
        <text class="form-label">修改密码</text>
        <view class="form-value-wrapper">
          <text class="form-value">********</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
      
      <!-- 注册时间 -->
      <view class="form-item">
        <text class="form-label">注册时间</text>
        <text class="form-value">{{ formatDate(userDetail.createTime) }}</text>
      </view>
    </view>
    
    <!-- 编辑弹窗 -->
    <uni-popup ref="editPopupRef" type="dialog">
      <uni-popup-dialog
        :title="editModalTitle"
        :mode="editModalMode"
        :before-close="true"
        @confirm="confirmEdit"
        @close="closeEditModal"
      >
        <!-- 手机号编辑 -->
        <template v-if="editType === 'phone'">
          <input 
            class="edit-input" 
            type="number" 
            v-model="editValue" 
            placeholder="请输入新手机号" 
            maxlength="11"
          />
        </template>
        
        <!-- 邮箱编辑 -->
        <template v-else-if="editType === 'email'">
          <input 
            class="edit-input" 
            type="text" 
            v-model="editValue" 
            placeholder="请输入新邮箱" 
          />
        </template>
        
        <!-- 密码编辑 -->
        <template v-else-if="editType === 'password'">
          <input 
            class="edit-input" 
            type="password" 
            v-model="oldPassword" 
            placeholder="请输入原密码" 
            maxlength="20"
          />
          <input 
            class="edit-input" 
            type="password" 
            v-model="newPassword" 
            placeholder="请输入新密码" 
            maxlength="20"
          />
        </template>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/store/user';
import http from '@/utils/http/http.js';
import { BASE_URL } from '@/config/env';

const userStore = useUserStore();
const statusBarHeight = ref(0);
const loading = ref(true);
const userDetail = ref({});
const userId = ref('');

// 编辑相关变量
const editPopupRef = ref(null);
const editType = ref('');
const editValue = ref('');
const oldPassword = ref('');
const newPassword = ref('');
const editModalTitle = ref('');
const editModalMode = ref('input');

// 获取状态栏高度
const getStatusBarHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync();
    statusBarHeight.value = systemInfo.statusBarHeight || 0;
  } catch (e) {
    console.error('获取系统信息失败:', e);
    statusBarHeight.value = 0;
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 获取用户详情
const getUserDetail = async () => {
  loading.value = true;
  
  try {
    // 检查登录状态
    if (!userStore.isLoggedIn || !userStore.token) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      uni.navigateBack();
      return;
    }
    
    // 发送请求
    const response = await http.get(`/api/users/${userId.value}`, {
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200 && response.data) {
      console.log('用户详情数据:', response.data);
      userDetail.value = response.data;
    } else {
      uni.showToast({
        title: response.message || '获取用户详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取用户详情失败:', error);
    uni.showToast({
      title: '获取用户详情失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      
      // 这里应该上传头像到服务器，然后更新用户信息
      // 由于没有上传接口，这里只做模拟
      uni.showLoading({
        title: '上传中...'
      });
      
      setTimeout(() => {
        uni.hideLoading();
        
        // 模拟更新头像
        updateUserInfo({
          avatarUrl: '/images/avatar/custom.jpg' // 假设这是上传后的路径
        });
      }, 1500);
    }
  });
};

// 显示编辑弹窗
const showEditModal = (type) => {
  editType.value = type;
  
  switch (type) {
    case 'phone':
      editModalTitle.value = '修改手机号';
      editValue.value = userDetail.value.phone || '';
      editModalMode.value = 'input';
      break;
    case 'email':
      editModalTitle.value = '修改邮箱';
      editValue.value = userDetail.value.email || '';
      editModalMode.value = 'input';
      break;
    case 'password':
      editModalTitle.value = '修改密码';
      oldPassword.value = '';
      newPassword.value = '';
      editModalMode.value = 'base';
      break;
  }
  
  if (editPopupRef.value) {
    editPopupRef.value.open();
  }
};

// 关闭编辑弹窗
const closeEditModal = () => {
  if (editPopupRef.value) {
    editPopupRef.value.close();
  }
};

// 确认编辑
const confirmEdit = () => {
  switch (editType.value) {
    case 'phone':
      if (!editValue.value) {
        uni.showToast({
          title: '手机号不能为空',
          icon: 'none'
        });
        return;
      }
      
      if (!/^1\d{10}$/.test(editValue.value)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return;
      }
      
      updateUserInfo({
        phone: editValue.value
      });
      break;
    case 'email':
      if (editValue.value && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(editValue.value)) {
        uni.showToast({
          title: '请输入正确的邮箱',
          icon: 'none'
        });
        return;
      }
      
      updateUserInfo({
        email: editValue.value
      });
      break;
    case 'password':
      if (!oldPassword.value || !newPassword.value) {
        uni.showToast({
          title: '密码不能为空',
          icon: 'none'
        });
        return;
      }
      
      if (newPassword.value.length < 6) {
        uni.showToast({
          title: '新密码长度不能小于6位',
          icon: 'none'
        });
        return;
      }
      
      updateUserInfo({
        oldPassword: oldPassword.value,
        newPassword: newPassword.value
      });
      break;
  }
  
  closeEditModal();
};

// 更新用户信息
const updateUserInfo = async (data) => {
  try {
    uni.showLoading({
      title: '更新中...'
    });
    
    const response = await http.put(`/api/users/${userId.value}`, data, {
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200) {
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      });
      
      // 重新获取用户详情
      getUserDetail();
      
      // 如果更新了头像或手机号，也需要更新用户状态
      if (data.avatarUrl || data.phone) {
        userStore.updateUserInfo({
          ...userStore.userInfo,
          ...(data.avatarUrl ? { avatar: data.avatarUrl } : {}),
          ...(data.phone ? { phone: data.phone } : {})
        });
      }
    } else {
      uni.showToast({
        title: response.message || '更新失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('更新用户信息失败:', error);
    uni.showToast({
      title: '更新失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知';
  
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 页面加载时执行
onMounted(() => {
  getStatusBarHeight();
  
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.$page?.options || {};
  
  if (options.id) {
    userId.value = options.id;
    getUserDetail();
  } else {
    uni.showToast({
      title: '用户ID不存在',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});
</script>

<style>
.container {
  background-color: #FFF9F2;
  min-height: 100vh;
}

.navbar {
  display: flex;
  align-items: center;
  height: 44px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  padding: 0 15px;
}

.navbar-left {
  width: 40px;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

.navbar-right {
  width: 40px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 100px 0;
}

.loading-text {
  margin-top: 15px;
  font-size: 14px;
  color: #999;
}

.user-form {
  margin: 20px;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border-radius: 10px;
  margin-bottom: 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.form-label {
  font-size: 15px;
  color: #333;
}

.form-value-wrapper {
  display: flex;
  align-items: center;
}

.form-value {
  font-size: 15px;
  color: #666;
  margin-right: 10px;
}

.avatar-item {
  align-items: center;
}

.avatar-wrapper {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 40px;
  overflow: hidden;
}

.avatar {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
}

.avatar-edit {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 30px;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.edit-input {
  height: 40px;
  border: 1px solid #eee;
  border-radius: 5px;
  padding: 0 10px;
  margin-bottom: 10px;
}

.edit-input:last-child {
  margin-bottom: 0;
}
</style>